# Copyright (c) 2025, zhn and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document


class PartsBreakdownList(Document):
	def validate(self):
		"""验证文档数据"""
		self.check_unique_record_id()
		self.validate_dimensions()
		self.set_creation_info()
	
	def check_unique_record_id(self):
		"""检查记录ID是否唯一"""
		if self.record_id:
			if frappe.db.exists("Parts Breakdown List", {"record_id": self.record_id, "name": ["!=", self.name]}):
				frappe.throw(f"记录ID {self.record_id} 已存在，请使用不同的记录ID")
	
	def validate_dimensions(self):
		"""验证尺寸数据"""
		if self.length and self.length <= 0:
			frappe.throw("长度必须大于0")
		
		if self.width and self.width <= 0:
			frappe.throw("宽度必须大于0")
		
		if self.thickness and self.thickness <= 0:
			frappe.throw("厚度必须大于0")
		
		if self.quantity and self.quantity <= 0:
			frappe.throw("件数必须大于0")
		
		if self.square_meters and self.square_meters <= 0:
			frappe.throw("平方数必须大于0")
	
	def set_creation_info(self):
		"""设置创建信息"""
		if not self.creation_time:
			self.creation_time = frappe.utils.now()
		
		if not self.created_by:
			self.created_by = frappe.session.user
		
		if not self.owner_field:
			self.owner_field = frappe.session.user
	
	def on_update(self):
		"""文档更新时触发"""
		self.last_modified_time = frappe.utils.now()
		self.last_modified_by = frappe.session.user
